<template>
  <div class="container">
    <h2>找回密码</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="email">邮箱：</label>
        <input 
          type="text" 
          id="email" 
          name="email" 
          v-model="resetForm.email"
          required
        >
      </div>
      <div class="verification-code">
        <input 
          type="text" 
          id="code" 
          name="code" 
          v-model="resetForm.verifyCode"
          placeholder="请输入验证码" 
          required
        >
        <button 
          type="button" 
          id="sendCodeBtn" 
          @click="sendCode" 
          :disabled="isSendingCode || isCountingDown"
        >
          {{ buttonText }}
        </button>
      </div>
      <div class="form-group">
        <label for="newPassword">新密码：</label>
        <input 
          type="password" 
          id="newPassword" 
          name="newPassword" 
          v-model="resetForm.newPassword"
          required
        >
      </div>
      <div class="form-group">
        <label for="confirmPassword">确认新密码：</label>
        <input 
          type="password" 
          id="confirmPassword" 
          name="confirmPassword" 
          v-model="resetForm.confirmPassword"
          @input="validatePasswords"
          required
        >
        <p class="error-tip" v-if="passwordError">{{ passwordError }}</p>
      </div>
      <button type="submit" class="btn" :disabled="loading">
        {{ loading ? '处理中...' : '重置密码' }}
      </button>
    </form>
    <div class="links">
      <router-link to="/login">返回登录</router-link> 
    </div>
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      resetForm: {
        email: '',
        verifyCode: '',
        newPassword: '',
        confirmPassword: ''
      },
      isSendingCode: false,
      isCountingDown: false,
      countdown: 60,
      buttonText: '获取验证码',
      passwordError: '',
      errorMessage: '',
      loading: false,
      returnVerifyCode: '' // 存储后端返回的验证码
    };
  },
  methods: {
    async handleSubmit() {
      // 验证密码一致性
      if (this.resetForm.newPassword !== this.resetForm.confirmPassword) {
        this.passwordError = '两次密码不一致';
        return;
      }
      
      // 验证验证码
      if (!this.returnVerifyCode || this.returnVerifyCode !== this.resetForm.verifyCode) {
        this.errorMessage = '验证码错误';
        return;
      }
      
      this.loading = true;
      this.errorMessage = '';
      
      try {
        // 构造请求数据
        const resetData = {
          userInput: this.resetForm.email,
          password: this.resetForm.newPassword,
          verifyCode: this.resetForm.verifyCode
        };
        
        // 调用后端 reset 接口
        const res = await axios.post('/api/login/reset', resetData);
        
        if (res.data.code !== 200) {
          throw new Error(res.data.message || '密码重置失败');
        }
        
        // 跳转到重置成功页面
      this.$router.push({
          path: '/resetSuccess',
          query: { email: this.resetForm.email }
  
      });
      } catch (err) {
        this.errorMessage = err.message || '密码重置失败，请重试';
      } finally {
        this.loading = false;
      }
    },
    
    async sendCode() {
      if (this.isSendingCode || this.isCountingDown) return;
      
      // 验证邮箱格式
      const regex = /^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
      if (!regex.test(this.resetForm.email)) {
        this.errorMessage = '邮箱格式不正确';
        return;
      }
      
      this.isSendingCode = true;
      this.errorMessage = '';
      
      try {
        // 发送验证码请求
        const res = await axios.post('/api/email/auth/sendCode', null, {
          params: {
            email: this.resetForm.email,
            typeCode: 'reset'
          }
        });
        
        if (res.data.code !== 200) {
          throw new Error(res.data.message || '发送验证码失败');
        }
        
        // 存储后端返回的验证码
        this.returnVerifyCode = res.data.data;
        
        // 启动倒计时
        this.startCountdown();
      } catch (err) {
        this.errorMessage = err.message || '发送验证码失败，请重试';
      } finally {
        this.isSendingCode = false;
      }
    },
    
    startCountdown() {
      this.isCountingDown = true;
      this.countdown = 60;
      this.buttonText = `${this.countdown}s后重试`;
      
      const timer = setInterval(() => {
        this.countdown--;
        this.buttonText = `${this.countdown}s后重试`;
        
        if (this.countdown <= 0) {
          clearInterval(timer);
          this.isCountingDown = false;
          this.buttonText = '获取验证码';
        }
      }, 1000);
    },
    
    validatePasswords() {
      if (this.resetForm.newPassword !== this.resetForm.confirmPassword) {
        this.passwordError = '两次密码不一致';
      } else {
        this.passwordError = '';
      }
    }
  }
};
</script>

<style src="../../assets/Reset.css">
</style>